﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.Productionorders;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.Productionorders;
using Reporting.Infrastructure.Interfaces.ProductTypes;

namespace Reporting.API.Application.CommandHandler.Productionorders
{
    public class UpdateProductionorderCommandHandler : IRequestHandler<UpdateProductionorderCommand, ApiResult>
    {
        private readonly IProductionorderRepository _productionorderRepository;
        private readonly IProductTypeRepository _productTypeRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddProductionorderCommandHandler> _logger;

        public UpdateProductionorderCommandHandler(ILogger<AddProductionorderCommandHandler> logger, IMapper mapper, IProductionorderRepository productionorderRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionorderRepository = productionorderRepository;
        }

        public async Task<ApiResult> Handle(UpdateProductionorderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询生产工单
                var ProductionorderPlans = await _productionorderRepository.GetAsync(x => x.Productionorderid == request.Productionorderid);

                if (ProductionorderPlans == null)
                {
                    return ApiResult.Fail("修改当前数据不存在", StatusCodeEnum.BadRequest);
                }


                // 更新生产工单
                var productionPlan = _mapper.Map(request, ProductionorderPlans);
                await _productionorderRepository.UpdateAsync(productionPlan);

                return ApiResult.Success(StatusCodeEnum.Success);


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生产工单修改失败");
                throw;
            }
        }
    }
}
